<template>
  <div>
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth';
import modal from '@/utils/modal';
import { download } from '@/utils/request';

const props = defineProps({
	// 导入地址
	importAction: {
		type: String,
		required: true
	},
	// 导入标题
	title: {
		type: String,
		default: '导入'
	},
	template: {
		type: String
	},
	
});


/** * 用户导入参数 */
const upload = ref({
	// 是否显示弹出层（用户导入）
	open: true,
	// 弹出层标题（用户导入）
	title: '',
	// 是否禁用上传
	isUploading: false,
	// 是否更新已经存在的用户数据
	updateSupport: 0,
	// 设置上传的请求头部
	headers: { Authorization: 'Bearer ' + getToken() },
	// 上传的地址
	url: computed(() => import.meta.env.VITE_APP_BASE_API + props.importAction),
});
// 成功导入
const emits = defineEmits(['isok']);

/** 下载模板操作 */
function importTemplate() {
	download(props.template, {}, `user_template_${new Date().getTime()}.xlsx`);
}
/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
	upload.value.isUploading = true;
};
/** 文件上传成功处理 */
const uploadRef = ref(null);
const handleFileSuccess = (response, file, fileList) => {
	upload.value.open = false;
	upload.value.isUploading = false;
	uploadRef.value.handleRemove(file);
	modal.alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true });
	emits('isok','1111');
};
/** 提交上传文件 */
function submitFileForm() {
	uploadRef.value.submit();
}
</script>

